package com.zx.config;/**
 * Author:JasonZ
 * Data:2023/4/20
 */

import cn.hutool.core.lang.UUID;
import com.zx.service.IAsyncGoodsService;
import com.zx.vo.GoodsInfo;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.swing.text.TabableView;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: ecommerce-parent
 * @description: 异步任务管理器
 * @author: JasonZ
 * @create: 2023-04-20 16:42
 **/
@Component
public class AsyncTaskManager {

    //存储任务的容器
    private final Map<String, AsyncTask> taskContainer = new HashMap<>();

    @Resource
    private IAsyncGoodsService asyncGoodsService;

    //初始化异步入库任务对象
    public AsyncTask initTask() {
        AsyncTask task = new AsyncTask();
        task.setId(UUID.randomUUID().toString());
        task.setAsyncTaskStatus(AsyncTaskStatus.STARTED);
        task.setStartTime(new Date());
        taskContainer.put(task.getId(), task);
        return task;
    }

    /**
     * 管理器执行异步任务
     *
     * @param goodsInfos
     * @return
     */
    public AsyncTask submit(List<GoodsInfo> goodsInfos) {
        //提交异步入库任务之后初始化并调用入库的service方法
        AsyncTask task = initTask();
        asyncGoodsService.asyncImportGoods(goodsInfos, task.getId());

        return task;
    }

    public void setTask(AsyncTask task) {
        this.taskContainer.put(task.getId(), task);
    }

    public AsyncTask getTask(String taskId) {
        return this.taskContainer.get(taskId);
    }
}
